import re

import redis


def get_datas(table_name, path, win_conn, db_conn):
    '''
    获取视图或表数据
    :param table_name: 表或视图名(例如：dbo_表名， View_视图名)
    :param path: 远程主机cube路径
    :return:
    '''
    redis_conn = redis.Redis(host='127.0.0.1', port=6379, db=12)
    redis_key = "{}-{}-dsv-fields".format(win_conn.host, path)
    if not redis_conn.get(redis_key):
        file_names = win_conn.get_files('*.dsv.xml', path)
        content = ''
        for file_name in file_names:
            if 'dsv' in file_name:
                content = win_conn.get_file_connect(file_name, path)
        redis_conn.set(redis_key, content, ex=60 * 60 * 24)  # ex参数设置60s过期
    else:
        content = redis_conn.get(redis_key).decode('utf-8')
    redis_conn.close()
    # 按<>匹配，找到量值名称所在<>
    pat = re.compile('<xs:element name="{}(.*?)msprop:QueryBuilder="SpecificQueryBuilder">'.format(table_name))
    content_list = pat.findall(content.replace('\r\n', ''))
    # 新策略
    sql_pat = re.compile('msprop:QueryDefinition="(.*)"')
    sql = ""

    if 'dbo_' not in table_name:
        for item in content_list:
            sql = sql_pat.findall(
                # 替换掉所有特殊符号
                item.replace('&#xD;&#xA;', ' ').replace('\r\n', ' ').replace("&lt;", '<').replace('&gt;', '>'))[0]
        fields = db_conn.get_dict_datas(sql)
        return fields
    else:
        replace_table_name = table_name.replace('dbo_', 'dbo.')
        sql = 'select * from {}'.format(replace_table_name)
        fields = db_conn.get_dict_datas(sql)
        return fields